﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model.WXshopBuiness;
using Services.WXshopBuiness;
using Services.Util;
using Model.Util;
using Xproject.Util;
using System.IO;
using Model.ZXBuiness;

namespace WeiXinpProAdmin.Controllers
{
    public class WXProductController : AdminBaseController
    {
        WXProductServices m_WXProductServices;
        UploadFileServices m_UploadFileServices;
        CategoryServices m_CategoryServices;
        public WXProductController(WXProductServices mWXProductServices, UploadFileServices mUploadFileServices, CategoryServices mCategoryServices)
        {
            m_WXProductServices = mWXProductServices;
            m_UploadFileServices = mUploadFileServices;
            m_CategoryServices = mCategoryServices;
        }

        #region ActionResult
        public ActionResult ProductRate( string productId)
        {
            ViewBag.ProductId = productId;
            ZXProductRate productRate = m_WXProductServices.GetProductRate(productId);
            return View(productRate);
        }
        /// <summary>
        /// 编辑产品提成比例
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public JsonResult EditProductRate(FormCollection collection)
        {

            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string Id = collection["Product_ZX_Rate_Id"];
            string productId = collection["ProductId"];
            ZXProductRate rate = new ZXProductRate();
            if (!string.IsNullOrEmpty(Id))
            {
                rate = m_WXProductServices.GetProductRate(productId);
            }
           
            rate.CreateTime = DateTime.Now;
            
         
            rate.P1Rate =decimal.Parse( collection["P1Rate"]);
            rate.P2Rate = decimal.Parse(collection["P2Rate"]);
            rate.P3Rate = decimal.Parse(collection["P3Rate"]);
            rate.P4Rate = decimal.Parse(collection["P4Rate"]);
            rate.P5Rate = decimal.Parse(collection["P5Rate"]);
            rate.P6Rate = decimal.Parse(collection["P6Rate"]);
            rate.P7Rate = decimal.Parse(collection["P7Rate"]);
            rate.P8Rate = decimal.Parse(collection["P8Rate"]);
            rate.P9Rate = decimal.Parse(collection["P9Rate"]);                          
            if (!string.IsNullOrEmpty(Id))
            {
                success = m_WXProductServices.EditProductRate(rate);
            }
            else //新增
            {
                success = m_WXProductServices.InsertProductRate(rate);
            }
            result = success ? "编辑成功" : "编辑失败";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        public ActionResult ProductSpecEdit(string SpecificationId,string productId)
        {
            ViewBag.ProductId = productId;
            ProductSpecification spec = m_WXProductServices.GetProductSpecification(SpecificationId);
            return View(spec);
        }
        public ActionResult ProductSpecList(string productId)
        {
            List<ProductSpecification> list = m_WXProductServices.GetProductSpecList(productId);
            ViewBag.productId = productId;
            return View(list);
        }
        public JsonResult EditProductSpeci(FormCollection collection)
        {

            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string Id = collection["SpecificationId"];
            ProductSpecification specification = new ProductSpecification();
            if (!string.IsNullOrEmpty(Id))
            {
                specification = m_WXProductServices.GetProdSpecById(Id);
            }
            else
            {
                specification.ProductSpecificationId = Guid.NewGuid().ToString();
            }
            specification.CreateTime = DateTime.Now;
            string Disable = collection["Disable"];
            specification.Enable = int.Parse(string.IsNullOrEmpty(Disable) ? "0" : ((Disable.ToString() == "on") ? "1" : "0"));
            specification.OrignPrice =decimal.Parse( collection["OrignPrice"].ToString());
            specification.SalesPrice =decimal.Parse( collection["SalesPrice"].ToString());
            specification.SpecificationName = collection["SpecificationName"];
            specification.Stock = int.Parse(collection["Stock"].ToString());
            specification.ProductId = collection["ProductId"];
            specification.Sort = int.Parse(collection["Sort"]);
            specification.CostPrice = decimal.Parse(collection["CostPrice"].ToString());

            specification.Remarks = collection["Remarks"];
            if (!string.IsNullOrEmpty(Id))
            {
                success = m_WXProductServices.EditProductSpecifation(specification);
            }
            else //新增
            {                               
                success = m_WXProductServices.AddProductSpecifation(specification);
            }
            result = success ? "编辑成功" : "编辑失败";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        public JsonResult DelProductSpec(string ProductSpecificationId)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            if (!string.IsNullOrEmpty(ProductSpecificationId))
            {
                ProductSpecification productspec = m_WXProductServices.GetProductSpecification(ProductSpecificationId);
                success = m_WXProductServices.DelProductSpec(productspec);
                result = success ? "删除成功" : "删除失败";               
            }
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        // GET: WXProduct
        public ActionResult ProductEdit(string productId)
        {
            WXProduct product = null;
            ViewBag.productId = null;          
            List<ProductContents> contents = new List<ProductContents>();
            ViewBag.batchId = Guid.NewGuid().ToString(); // 上传文件批次 
            int uploadedPicCount = 0;
            if (!string.IsNullOrEmpty(productId))
            {
                product = m_WXProductServices.GetById(productId);
                ViewBag.productId = productId;
                
                contents = m_WXProductServices.GetProductContent(productId);
            }
            Cache_ComUtil.SetBatchCount(ViewBag.batchId, uploadedPicCount);
            ViewData["contents"] = contents;             
            ViewData["categoryList"] = m_CategoryServices.GetAllCategory();
            return View(product);
        }

        public ActionResult ProductList()
        {
            ViewData["categoryList"] = m_CategoryServices.GetAllCategory();
            return View();
        }

        public ActionResult ProductCommentList()
        {
            return View();
        }

        public ActionResult ProductCommentEdit(string commentId,string productId)
        {
            ProductComments comments = null;
            if (!string.IsNullOrEmpty(commentId))
            {
                comments = m_WXProductServices.GetCommentById(commentId);
            }
            ViewBag.productId = productId;
            if (!string.IsNullOrEmpty(productId))
            {
                 WXProduct product =  m_WXProductServices.GetById(productId);
                ViewBag.ProductCode = product.ProductCode;
                ViewBag.ProductName = product.ProductName;
            }
            return View(comments);

        }

        #endregion

        #region JsonResult

            #region 商品相关
        public JsonResult GetWXProductList(int limit, int offset, string productName, string  productCode, string productDesc, string key,
            int? isSheepFree,string remarks,int? state,int?  categoryID,DateTime? startTime, DateTime? endTime, string order, string ordername)
        {
            var jsonData = new Object();
            var lstRes = new List<WXProduct>();
            int total = 0;
            lstRes = m_WXProductServices.GetAllWXProducts(Site, offset, limit, productName, productCode, productDesc, key, isSheepFree,
                remarks, state, categoryID,startTime, endTime, order, ordername, out total);
            return Json(new { total = total, rows = lstRes }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult EditWXProduct(FormCollection collection)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;          
            string productID = collection["ProductID"];
            WXProduct product = new WXProduct();
            List<ProductContents> AddproductContents = new List<ProductContents>();
            List<ProductContents> EditproductContents = new List<ProductContents>();
            List<UploadFile> ufs = new List<UploadFile>();
            if (!string.IsNullOrEmpty(productID))
            {
                product = m_WXProductServices.GetById(productID);
            }
            else
            {
                product.Domain = Domain;
                product.ProductID = Guid.NewGuid().ToString();
                product.ProductCode = m_WXProductServices.CreateProductCode(collection["ProductCode"],product.ProductID);
            }
            #region 
            //图文详细内容                
            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection FileCollect = request.Files;
            string Virbase = @"Upload\Images\";
            string DataTimeFolder = DateTime.Now.ToString("yyyyMMdd");
            string localpath = AppDomain.CurrentDomain.BaseDirectory + Virbase;
            string Folder = localpath + DataTimeFolder;
            if (!Directory.Exists(Folder))
                Directory.CreateDirectory(Folder);

            if (FileCollect.Count > 0) //如果集合的数量大于0 
            {
                foreach (string str in FileCollect)
                {
                 
                    HttpPostedFile FileSave = FileCollect[str]; //用key获取单个文件对象HttpPostedFile 
                    UploadFile uf = new UploadFile();
                    uf.FileName = FileSave.FileName;
                    uf.FileExt = Path.GetExtension(FileSave.FileName);
                    uf.FileSize = FileSave.ContentLength;
                    uf.Site = Site;
                    uf.ServiceAddress = CommonHelper.GetAppSettings("Domain");
                    string guidName = Guid.NewGuid().ToString() + uf.FileExt;
                    uf.Path = ("\\" + Virbase + DataTimeFolder + "\\" + guidName).Replace("\\", "/");
                    uf.FileId = Guid.NewGuid().ToString();
                    string LocalFullPath = Folder + @"\" + guidName;
                    if (str == "productVideo")
                    {
                        Virbase = @"Upload\Video\";
                        uf.Path = ("\\" + Virbase + DataTimeFolder + "\\" + guidName).Replace("\\", "/");
                        localpath = AppDomain.CurrentDomain.BaseDirectory + Virbase;
                        Folder = localpath + DataTimeFolder;
                        if (!Directory.Exists(Folder))
                            Directory.CreateDirectory(Folder);
                        LocalFullPath = Folder + @"\" + guidName;
                        uf.LocalFullPath = LocalFullPath;
                        FileSave.SaveAs(LocalFullPath); //将上传的东西保存  
                        ufs.Add(uf);
                        product.VideoUrl = uf.Path;
                        if (uf.FileExt.Contains("mp4"))
                        {
                            product.VideoType = "video/mp4";
                        }
                        else if (uf.FileExt.Contains("webm"))
                        {
                            product.VideoType = "video/webm";
                        }
                        else
                        {
                            product.VideoType = "video/ogg";
                        }
                    }
                    if(str.Contains( "productContentImg"))
                    {
                        uf.LocalFullPath = LocalFullPath;
                        FileSave.SaveAs(LocalFullPath); //将上传的东西保存    
                        string strStand = "productContentImg";
                        string strStandC = "productContent";
                        int ContentIndex = 0;
                        int.TryParse((str.Substring(strStand.Length, (str.Length - strStand.Length))), out ContentIndex);
                        uf.Spec = ContentIndex.ToString();

                        //如果已经有过了的，就是修改
                        List<ProductContents> alreadProductContents = new List<ProductContents>();
                        if (!string.IsNullOrEmpty(productID))
                        {
                            alreadProductContents = m_WXProductServices.GetProductContent(productID);
                        }
                        
                        ProductContents  pcontents = alreadProductContents.Where(i => i.ProductIndex == ContentIndex).FirstOrDefault();
                        if (pcontents == null)
                        {
                            pcontents = new ProductContents();
                            pcontents.ID = Guid.NewGuid().ToString();
                            pcontents.ProductImage = uf.Path;
                            pcontents.Domain = uf.ServiceAddress;
                            pcontents.ProductContent = collection[strStandC + ContentIndex];
                            pcontents.ProductContentID = Guid.NewGuid().ToString();
                            pcontents.ProductID = product.ProductID;
                            pcontents.ProductIndex = ContentIndex;
                            pcontents.Type = 1;
                            AddproductContents.Add(pcontents);
                        }
                        else
                        {
                            pcontents.ProductImage = uf.Path;
                            pcontents.Domain = uf.ServiceAddress;
                            pcontents.ProductContent = collection[strStandC + ContentIndex];                         
                            pcontents.ProductID = product.ProductID;
                            pcontents.ProductIndex = ContentIndex;
                            pcontents.Type = 1;
                            EditproductContents.Add(pcontents);
                        }
                        
                        ufs.Add(uf);
                        
                    }
                    if (str.Contains("ImageUrl"))
                    {
                        uf.LocalFullPath = LocalFullPath;
                        FileSave.SaveAs(LocalFullPath); //将上传的东西保存   
                        switch (str) {
                            case "ImageUrl1":
                                {
                                    product.ImageUrl1 = uf.Path;
                                    product.FileId1 = uf.FileId;
                                    if (product.ImageUrl1 != "")
                                    {
                                        int start = product.ImageUrl1.IndexOf('.');
                                        int len = product.ImageUrl1.Length - start;
                                        string ext = product.ImageUrl1.Substring(start, len);
                                        string Virbase2 = @"Upload\ThmbImages\";
                                        string localpath2 = AppDomain.CurrentDomain.BaseDirectory + Virbase2;

                                        string Folder2 = localpath2 + DataTimeFolder;
                                        if (!Directory.Exists(Folder2))
                                            Directory.CreateDirectory(Folder2);
                                        string localThumbnail = Folder2 + @"\" + uf.FileId + ext;
                                        ImageHelper.MakeThumbnail(uf.LocalFullPath, localThumbnail, 100, 100, "HW");
                                        string thumbpath = ("\\" + Virbase2 + DataTimeFolder + "\\" + uf.FileId + ext).Replace("\\", "/");
                                        product.ThumbnailUrl1 = thumbpath;
                                        product.Domain = Domain;
                                    }
                                    break;
                                }
                            case "ImageUrl2": product.ImageUrl2 = uf.Path; product.FileId2 = uf.FileId; break;
                            case "ImageUrl3": product.ImageUrl3 = uf.Path; product.FileId3 = uf.FileId; break;
                            case "ImageUrl4": product.ImageUrl4 = uf.Path; product.FileId4 = uf.FileId; break;
                            case "ImageUrl5": product.ImageUrl5 = uf.Path; product.FileId5 = uf.FileId; break;
                            case "ImageUrl6": product.ImageUrl6 = uf.Path; product.FileId6 = uf.FileId; break;
                            case "ImageUrl7": product.ImageUrl7 = uf.Path; product.FileId7 = uf.FileId; break;
                            case "ImageUrl8": product.ImageUrl8 = uf.Path; product.FileId8 = uf.FileId; break;
                            case "ImageUrl9": product.ImageUrl9 = uf.Path; product.FileId9 = uf.FileId; break;
                            default:break;
                        }
                        ufs.Add(uf);
                    }


                }
            }
            #endregion

            #region  标准内容
            product.ProductName = collection["ProductName"];
            product.ShortDesc = collection["ShortDesc"];
            product.ShowOnWhere = collection["ShowOnWhere"];
            product.ShowStyle = collection["ShowStyle"];            
            product.SortID = int.Parse(collection["SortID"]);
            product.ProductKeyword = collection["ProductKeyword"];
            product.MarketPrice = decimal.Parse(collection["MarketPrice"]);
            product.CostPrice =decimal.Parse( collection["CostPrice"]);
            product.SalePrice = decimal.Parse(collection["SalePrice"]);
            product.VistiCounts = int.Parse(collection["VistiCounts"]);
            product.SaleCounts = int.Parse(collection["SaleCounts"]);
            product.Stock = int.Parse(collection["Stock"]);
            product.IsFreeShipping = int.Parse(collection["IsFreeShipping"]);
            product.CategoryID =int.Parse( collection["CategoryID"]);
            product.CategoryName = "顶层分类";
            product.Spec1 = collection["Spec1"];
            product.Spec2 = collection["Spec2"];
            product.Spec3 = collection["Spec3"];

            #endregion  
            if (product.CategoryID!=0)
            {
                Category cg = m_CategoryServices.GetCategoryById(product.CategoryID);
                product.CategoryName = cg.Name;
             }
                    
            
            product.Site = Site;
            product.State =int.Parse( collection["State"]);
            product.Remark = collection["Remark"];
            //上传的轮播图片
            string UploadFileIds = collection["UploadFileIds"];

            if (!string.IsNullOrEmpty(UploadFileIds))
            {
                product.PicFileIds = UploadFileIds;
                List<string> fileIds = UploadFileIds.Split(';').ToList();
                List<UploadFile> pics= m_UploadFileServices.GetUploadFiles(Site, fileIds);
                if (pics != null && pics.Count > 0)
                {
                    pics = pics.OrderBy(i => i.Spec).ToList();
                    product.ImageUrl1 = (pics.Count >= 1) ? (  pics[0].Path) : "";
                    product.FileId1 = (pics.Count >= 1) ? (pics[0].FileId) : "";
                    product.ImageUrl2 = (pics.Count >= 2) ? (  pics[1].Path) : "";
                    product.FileId2 = (pics.Count >= 2) ? (pics[1].FileId) : "";
                    product.ImageUrl3 = (pics.Count >= 3) ? (  pics[2].Path) : "";
                    product.FileId3 = (pics.Count >= 3) ? (pics[2].FileId) : "";
                    product.ImageUrl4 = (pics.Count >= 4) ? (  pics[3].Path) : "";
                    product.FileId4 = (pics.Count >= 4) ? (pics[3].FileId) : "";
                    product.ImageUrl5 = (pics.Count >= 5) ? (  pics[4].Path) : "";
                    product.FileId5 = (pics.Count >= 5) ? (pics[4].FileId) : "";
                    product.ImageUrl6 = (pics.Count >= 6) ? (  pics[5].Path) : "";
                    product.FileId6 = (pics.Count >= 6) ? (pics[5].FileId) : "";
                    product.ImageUrl7 = (pics.Count >= 7) ? (  pics[6].Path) : "";
                    product.FileId7 = (pics.Count >= 7) ? (pics[6].FileId) : "";
                    product.ImageUrl8 = (pics.Count >= 8) ? (  pics[7].Path) : "";
                    product.FileId8 = (pics.Count >= 8) ? (pics[7].FileId) : "";
                    product.ImageUrl9 = (pics.Count >= 9) ? (  pics[8].Path) : "";
                    product.FileId9 = (pics.Count >= 9) ? (pics[8].FileId) : "";
                    if (product.ImageUrl1 != "")
                    {
                        int start = product.ImageUrl1.IndexOf('.');
                        int len = product.ImageUrl1.Length - start;
                        string ext = product.ImageUrl1.Substring(start, len);
                        string Virbase2 = @"Upload\ThmbImages\";                        
                        string localpath2 = AppDomain.CurrentDomain.BaseDirectory + Virbase2;
                       
                        string Folder2 = localpath2 + DataTimeFolder;
                        if (!Directory.Exists(Folder2))
                            Directory.CreateDirectory(Folder2);
                        string localThumbnail = Folder2 + @"\" + pics[0].FileId + ext;
                        ImageHelper.MakeThumbnail(pics[0].LocalFullPath, localThumbnail, 100, 100, "HW");
                        string thumbpath = ("\\" + Virbase2 + DataTimeFolder + "\\" + pics[0].FileId + ext).Replace("\\", "/");
                        product.ThumbnailUrl1 =   thumbpath;
                        product.Domain = Domain;
                    }
                }
                
            }
           
            if (!string.IsNullOrEmpty(productID)) // 如果 Id 不为空，说明是编辑
            {
                success = m_WXProductServices.EditWXProduct(product, ufs, AddproductContents,EditproductContents, CurrentUser.UserID.ToString());
                if (success) { Cache_Product.ClearWXProduct(); }
                result = (success) ? "编辑产品成功！" : "编辑产品失败！";
            }
            else //新增产品
            {

                success = m_WXProductServices.AddWXProduct(product,ufs, AddproductContents, CurrentUser.UserID.ToString());
                if (success) { Cache_Product.ClearWXProduct(); }
                result = (success) ? "添加产品成功！" : "添加产品失败！";
            }

            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ProductCategoryAttrEdit(string productId,int categoryId)
        {
             List<CategoryAttrGroups> groups= m_CategoryServices.GetAttributeGroupListByCateId(categoryId,null);
             List<CategoryAttr> attrs =m_CategoryServices.GetAttributeListByCateId(categoryId);
            List<CategoryAttrValues> attrvalues = new List<CategoryAttrValues>();
            if (attrs != null && attrs.Count > 0)
            {
                attrvalues =  m_CategoryServices.GetAttributeValueListByAttrId(attrs.Select(i =>i.AttrId).ToList());
            }
            ViewData["grooup"] = groups;
            ViewData["attrs"] = attrs;
            ViewData["attrvalues"] = attrvalues;
            ViewBag.productId = productId;
            List<WeiXinProductAttr> exitsattr = m_WXProductServices.GetProductAttrs(productId);
            List<int> existattrvalueIds = new List<int>();
            Dictionary<int, string> inputValue = new Dictionary<int, string>();
            if (exitsattr != null && exitsattr.Count > 0)
            {
                existattrvalueIds= exitsattr.Select(i => i.AttrValueId).ToList();
                foreach (WeiXinProductAttr t in exitsattr)
                {
                    if (t.IsInput == 1)
                    {
                        inputValue.Add(t.AttrValueId, t.Inputvalue);
                    }
                }
            }
            ViewData["existsAttrValueIds"] = existattrvalueIds;
            ViewData["inputValue"] = inputValue;
            return View();
        }

        [HttpPost]
        public JsonResult EditProductAttr(List<WeiXinProductAttrModel> productAttrs, string productId) {
          var jsonData = new Object();
           string result = string.Empty;
           bool success = false;
            List<WeiXinProductAttr> newproductattr = new List<WeiXinProductAttr>();
            foreach (WeiXinProductAttrModel model in productAttrs)
            {
                WeiXinProductAttr temp = new WeiXinProductAttr();
                temp.AttrId = model.AttrId;
                temp.AttrValueId = model.AttrValueId;
                temp.IsInput = model.IsInput;
                temp.ProductId = model.ProductId;
                temp.Inputvalue = model.Inputvalue;
                newproductattr.Add(temp);
            }
            success= m_WXProductServices.EditProductAttr(newproductattr, productId);
            result = success ? "编辑属性成功" : "编辑属性失败";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DelProductComment(string commentId)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            if (!string.IsNullOrEmpty(commentId))
            {
                ProductComments productcomments = m_WXProductServices.GetCommentById(commentId);
                success = m_WXProductServices.DelWXProductComment(productcomments);
                result = success ? "删除成功" : "删除失败";
               // if (success) { Cache_Product.ClearWXProduct(); }
            }
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DelWXProduct(string productId)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            if (!string.IsNullOrEmpty(productId))
            {
                WXProduct product = m_WXProductServices.GetById(productId);
                success = m_WXProductServices.DelWXProduct(product);
                result = success ? "删除成功" : "删除失败";
                if (success) { Cache_Product.ClearWXProduct(); }
            }
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
            #endregion

            #region 商品评论相关
        public JsonResult GetWXProductCommentList(int limit, int offset, string productName, string productCode,  
           DateTime? startTime, DateTime? endTime, string order, string ordername)
        {
            var jsonData = new Object();
            var lstRes = new List<ProductComments>();
            int total = 0;
            lstRes = m_WXProductServices.GetAllProductComments(Site, offset, limit, productName, productCode,  
                 startTime, endTime, order, ordername, out total);
            return Json(new { total = total, rows = lstRes }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult EditProductComment(FormCollection collection)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;         
            string Id = collection["ID"];
            ProductComments comments = new ProductComments();
            if (!string.IsNullOrEmpty(Id))
            {
                comments = m_WXProductServices.GetCommentById(Id);
            }

            UploadFile uf = null;
            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection FileCollect = request.Files;
         

            if (FileCollect.Count > 0) //如果集合的数量大于0 
            {
                    string Virbase = @"Upload\Images\";
                    string DataTimeFolder = DateTime.Now.ToString("yyyyMMdd");
                    string localpath = AppDomain.CurrentDomain.BaseDirectory + Virbase;
                    string Folder = localpath + DataTimeFolder;
                    if (!Directory.Exists(Folder))
                        Directory.CreateDirectory(Folder);
                    HttpPostedFile FileSave = FileCollect[0]; //用key获取单个文件对象HttpPostedFile 
                    uf = new UploadFile();
                    uf.FileName = FileSave.FileName;
                    uf.FileExt = Path.GetExtension(FileSave.FileName);
                    uf.FileSize = FileSave.ContentLength;
                    uf.Site = Site;
                    uf.ServiceAddress = CommonHelper.GetAppSettings("Domain");
                    string guidName = Guid.NewGuid().ToString() + uf.FileExt;
                    uf.Path = ("\\" + Virbase + DataTimeFolder + "\\" + guidName).Replace("\\", "/");
                    uf.FileId = Guid.NewGuid().ToString();
                    string LocalFullPath = Folder + @"\" + guidName;
                    uf.LocalFullPath = LocalFullPath;
                    FileSave.SaveAs(LocalFullPath); //将上传的东西保存       
                    string Virbase2 = @"Upload\ThmbImages\";
                    string localpath2 = AppDomain.CurrentDomain.BaseDirectory + Virbase2;

                    string Folder2 = localpath2 + DataTimeFolder;
                    string localThumbnail = Folder2 + @"\" + uf.FileId + uf.FileExt;
                if (!Directory.Exists(Folder2))
                    Directory.CreateDirectory(Folder2);
                ImageHelper.MakeThumbnail(uf.LocalFullPath, localThumbnail, 100, 100, "HW");
                    string thumbpath = ("\\" + Virbase2 + DataTimeFolder + "\\" + uf.FileId + uf.FileExt).Replace("\\", "/");
                    comments.Domain = uf.ServiceAddress;
                    comments.UserImgUrl = thumbpath;
            }
            
           
           
            comments.Comment = collection["Comment"];
            comments.CommentIndex = int.Parse(collection["CommentIndex"]);
            comments.CommentLogisticStarts = int.Parse(collection["CommentLogisticStarts"]);
            comments.CommentPackageStarts = int.Parse(collection["CommentPackageStarts"]);
            comments.CommentServiceStarts = int.Parse(collection["CommentServiceStarts"]);
            comments.CommentTotalStarts = int.Parse(collection["CommentTotalStarts"]);            
            string enable = collection["Enable"];
            comments.Enable = int.Parse(string.IsNullOrEmpty(enable) ? "0" : ((enable.ToString() == "on") ? "1" : "0"));
            comments.ProductCode = collection["ProductCode"];
          //  comments.ProductName = collection["ProductName"];
            comments.UserId = "abcd"; // to do 
            comments.UserName = collection["UserName"];
            string createtime = collection["CreateTime"];            
            comments.CreateTime =  string.IsNullOrEmpty(createtime)?DateTime.Now: DateTime.Parse(createtime);
            string productID = collection["ProductID"];
            if(string.IsNullOrEmpty(productID))
            {
                var product =  m_WXProductServices.GetByProductCode(comments.ProductCode);
                if (product != null && product.ProductID != "")
                {
                    comments.ProductID = product.ProductID;
                    comments.ProductName = product.ProductName;
                }
                else
                {
                    jsonData = new { Success = false, Data = "此产品code产品 不存在" };
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
            }

            if (!string.IsNullOrEmpty(Id))
            {
                success = m_WXProductServices.EditProductComments(comments,uf,CurrentUser.UserID.ToString());
            }
            else
            {
                success = m_WXProductServices.AddProductComments(comments,uf,CurrentUser.UserID.ToString());
            }
                
            result = success ? "编辑成功" : "编辑失败";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
            #endregion

        #endregion
    }
}